import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServerThread{
    private ServerSocket serverSocket = null;
    public TcpEchoServerThread(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("server start!");
        //处理连接
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new ClientHandle(socket)).start();
        }

    }

    public static class ClientHandle implements Runnable{
        private Socket socket;
        public ClientHandle(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            //处理连接过程

            try {
                processConnection(socket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

        private void processConnection(Socket socket) throws IOException {
            System.out.printf("[%s:%d] 客户端上线\n",socket.getInetAddress(),socket.getPort());
            //1. 读取请求
            try (InputStream inputStream = socket.getInputStream();
                 OutputStream outputStream = socket.getOutputStream()) {

                Scanner scanner = new Scanner(inputStream);

                while (true) {
                    if (!scanner.hasNext()) {
                        System.out.printf("[%s:%d] 客户端下线\n",socket.getInetAddress(),socket.getPort());
                        break;
                    }

                    //2. 解析请求
                    String request = scanner.next();
                    String response = process(request);

                    //3. 发送数据报
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.println(response);
                    writer.flush();

                    //4. 打印日志
                    System.out.printf("[%s:%d],req: %s,resp: %s\n",socket.getInetAddress(),socket.getPort(),
                            request,response);
                }

            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                socket.close();
            }
        }

        private String process(String request) {
            return request;
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServerThread tcpEchoServerThread = new TcpEchoServerThread(6666);
        tcpEchoServerThread.start();
    }
}
